import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import subprocess

class ImageTransferApp:
    def __init__(self, root):
        self.root = root
        self.root.title("图片传输工具")

        frame = tk.Frame(self.root)
        frame.pack(pady=20, padx=20)

        tk.Label(frame, text='传入图片张数').grid(row=1, column=6, sticky=tk.NSEW, pady=10, padx=5)
        self.CANSHUSensorSelect = ttk.Combobox(frame, width=20, state='readonly', values=['1', '5'])
        self.CANSHUSensorSelect.grid(row=1, column=7, sticky=tk.NSEW, pady=5, padx=5, columnspan=2)
        self.CANSHUSensorSelect.current(0)

        tk.Label(frame, text='图片路径:').grid(row=0, column=10, sticky=tk.NSEW, padx=10, pady=5)
        self.PicEntry = tk.Entry(frame, width=20)
        self.PicEntry.grid(row=0, column=11, sticky=tk.NSEW, padx=10, pady=5, columnspan=2)
        tk.Button(frame, text='...', command=self.select_pic).grid(row=0, column=14, sticky=tk.NSEW, padx=10, pady=5)

        tk.Button(frame, text='一键导入', command=self.transfer_images).grid(row=1, column=9, sticky=tk.NSEW, pady=6, padx=5)

    def select_pic(self):
        folder_selected = filedialog.askdirectory()
        self.PicEntry.delete(0, tk.END)
        self.PicEntry.insert(0, folder_selected)

    def pullpictopath(self, picnum, path):
        cmd = 'adb shell "cd sdcard/DCIM/Camera; ls -t"'
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        p.wait()
        res = p.stdout.read()
        print('[Info]', '图片列表:')
        print(res, '\n')
        piclist = res.split('\n')
        cmd2 = ''
        if picnum >= len(piclist):
            cmd2 = 'adb pull sdcard/DCIM/Camera {};'.format(path)
        else:
            for i in range(picnum):
                cmd2 = cmd2 + 'adb pull sdcard/DCIM/Camera/{} {};'.format(piclist[i], path)
        p = subprocess.Popen(cmd2[:-1], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        p.wait()
        print(p.stdout.read())
        messagebox.showinfo("传输完成", "图片传输完成")

    def transfer_images(self):
        picnum = int(self.CANSHUSensorSelect.get())
        save_path = self.PicEntry.get()  # 获取用户输入的路径
        if not save_path:
            messagebox.showwarning("警告", "请输入图片保存路径")
            return
        self.pullpictopath(picnum, save_path)

if __name__ == "__main__":
    root = tk.Tk()
    app = ImageTransferApp(root)
    root.mainloop()
